<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<%
	String path = request.getContextPath();
	String basePath = request.getServerName() + ":"
			+ request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>总排行</title>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/common/table.css">
    <%@include file="../include/commonFile.jsp" %>
	<style type="text/css">
		.schedule-list {
			margin-top: 5px;
		}
		.schedule-list .schedule-item {
			margin-bottom: 5px;
		}
	</style>
</head><body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <div class="layui-tab layui-tab-brief mt20">
            	<ul class="layui-tab-title">
                    <li class="layui-this" id="总排行">总排行</li>
                    <li class="" id="groupRank">队伍排行</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item  layui-show">
			            <form class="layui-form" action="${ctx}/competition/result/personalRank.do?projectId=${project.id}" id="myForm" method="post">
			                <input type="hidden" name="pageNo" id="pageNo"/>
			                <div class="f-search-bar">
			                    <div class="search-container">
			                        <ul class="search-form-content">
			                        	<li class="form-item-inline"><label class="search-form-lable">赛程</label>
											<div class="layui-input-inline">
												<select name="scheduleId">
													<option value="">总赛程</option>
													<c:forEach var="schedule" items="${schedules}">
														<option value="${schedule.id}" ${rankInput.scheduleId == schedule.id ? 'selected="selected"' : ''}><fmt:formatDate value="${schedule.playDay}" pattern="yyyy年MM月dd日"/></option>
													</c:forEach>
												</select>
											</div>
										</li>
										<li class="form-item-inline"><label class="search-form-lable">队伍</label>
											<div class="layui-input-inline">
												<select name="groupId">
													<option value="">全部</option>
													<c:forEach var="group" items="${groups}">
														<option value="${group.id}" ${rankInput.groupId == group.id ? 'selected="selected"' : ''}>${group.groupName}</option>
													</c:forEach>
												</select>
											</div>
										</li>
										<li class="form-item-inline"><label class="search-form-lable">性别</label>
											<div class="layui-input-inline">
												<select name="sex">
													<option value="">全部</option>
													<option value="1" ${rankInput.sex == 1 ? 'selected="selected"' : ''}>男</option>
													<option value="0" ${rankInput.sex == 0 ? 'selected="selected"' : ''}>女</option>
												</select>
											</div>
										</li>
									</ul>
									<ul class="search-form-content">
										<li class="form-item-inline"><label class="search-form-lable">姓名</label>
											<div class="layui-input-inline">
												<input type="text" name="fullName" autocomplete="off"
													   class="layui-input" value="${rankInput.fullName}"
													   placeholder="请输入查询姓名" style="width: 195px">
											</div>
										</li>
										<li class="form-item-inline" style="margin-left: -89px;">
											<label class="search-form-lable">号码牌</label>
											<div class="layui-input-inline">
												<input type="text" name="numberPai" autocomplete="off"
													   class="layui-input" value="${rankInput.numberPai}"
													   placeholder="请输入查询号码牌" style="width: 195px">
											</div>
										</li>
										<li class="form-item-inline">
											<div class="sub-btns">
												<a class="layui-btn layui-btn-danger"
												   href="javascript:submitFunction('#myForm')">查询</a>
												<a class="layui-btn layui-btn-normal"
												   href="javascript:resetFunction('#myForm')">重置</a>
											</div>
										</li>
									</ul>
								</div>
							</div>
			            </form>
			            <div class="my-act-list-content">
			            	<ul class="num">
                                <div class="r">
                                    <li style="cursor: pointer;" class="r">
										<a class="layui-btn layui-btn-danger layui-btn-sm" id="resultSetBtn">成绩设置</a>
                                        <a class="layui-btn layui-btn-danger layui-btn-sm" id="exportExcelBtn">导出EXCEL</a>
										<a class="layui-btn layui-btn-danger layui-btn-sm" id="downloadTemplateBtn">下载人员成绩导入模板</a>
										<a class="layui-btn layui-btn-danger layui-btn-sm" id="importResultBtn">导入人员成绩EXCEL</a>
										<form id="userForm" method="post" class="dn" action="${ctx}/competition/result/personResultImport.do" enctype="multipart/form-data">
											<input type="file" name="uploadFile" id="upload_input" single
												   accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
											<input type="hidden" name="projectId" value="${project.id}"/>
										</form>
                                    </li>
                                </div>
                                <p class="cl"></p>
                            </ul>
			                <div class="cl">
			                    <table class="layui-table">
			                        <colgroup>
										<col width="60px">
										<col>
										<col>
										<col>
										<col width="90px">
										<col width="90px">
										<col width="150px">
										<col width="90px">
										<col width="90px">
			                        </colgroup>
			                        <thead>
				                        <tr>
				                            <th>排名</th>
				                            <th>所属队伍</th>
				                            <th>用户</th>
				                            <th>姓名</th>
											<th>性别</th>
				                            <th>号码牌</th>
				                            <th>比赛成绩</th>
				                            <th>里程</th>
				                            <th>状态</th>
				                        </tr>
			                        </thead>
			                        <tbody>
				                        <c:forEach var="memberResult" items="${memberResults}" varStatus="status">
				                            <tr>
				                            	<td><fmt:formatNumber value="${memberResult.rowno}" maxFractionDigits="0"></fmt:formatNumber></td>
				                            	<td>${memberResult.groupName}</td>
												<td class="table-member"
													onclick="openDialogShow('用户名片','${ctx}/system/member/memberView.do?id=${memberResult.member.id}','400px','470px')">
													<div class="member-cell">
														<div class="member-logo common-img">
															<c:if test="${not empty memberResult.member.logo}">
																<img src="<c:if test="${ memberResult.member.logo!= null}">${memberResult.member.logo}?imageMogr2/auto-orient/crop/126x126</c:if>" alt="" onerror="txz.errImg(this)" onload="txz.imgLoad(this)">
															</c:if>
															<c:if test="${empty memberResult.member.logo}">
																<img src="" alt="" onerror="txz.errImg(this)" onload="txz.imgLoad(this)">
															</c:if>
														</div>
														<div class="member-name ellipsis-1">
															<a class="blue" title="${memberResult.member.realname}" href="javascript:void(0);">${memberResult.member.realname}</a>
														</div>
													</div>
												</td>
				                            	<td>${empty memberResult.fullName ? memberResult.realName : memberResult.fullName}</td>
												<td>
														${memberResult.sex == 1 ? '男' : ''}
														${memberResult.sex == 0 ? '女' : ''}
												</td>
				                            	<td>${memberResult.numberPai}</td>
				                            	<td>${empty memberResult.result ? '00:00:00' : memberResult.result}</td>
				                            	<td>${empty memberResult.distance ? '0' : memberResult.distance}</td>
				                            	<td>${memberResult.isComplete == 1 ? '完赛' : '未完赛'}</td>
				                            </tr>
				                        </c:forEach>
			                        </tbody>
			                    </table>
			                    <c:if test="${page.totalCount == 0}">
									<div class="f16 tc mt15">还没有参赛人员</div>
								</c:if>
								<div class="page-content">
									<div id="page_content" class="page-container"></div>
								</div>
			                </div>
			            </div>
            		 </div>
            		 <div class="layui-tab-item"></div>
           		</div>
           </div>
        </div><!--底部-->
		<%@include file="../include/footer.jsp" %>
    </section>
	<div id="settingForm" class="layui-form p10" style="display: none">
		<div>请选择赛事阶段计算成绩</div>
		<div class="schedule-list">
			<c:forEach var="schedule" items="${schedules}">
				<div class="schedule-item" data-id="${schedule.id}">
					<input type="checkbox" lay-skin="primary"
						   title="<fmt:formatDate value='${schedule.playDay}' pattern="MM/dd"/> "
						${schedule.openStatus == 1 ? 'checked' : ''}
					/>
				</div>
			</c:forEach>
		</div>
	</div>
</div>

<script type="text/javascript" src="${ctx}/script/common/list.js"></script>
<script type="text/javascript" src="${ctx}/script/common/table_option.js"></script>
<script type="text/javascript">
    showActive('${input.createStart}', '${input.createEnd}', '#timeType');
    var myLoadIndex;
    $(function () {
		//加载分页
        loadPageNew({
            elem: 'page_content',
            totalCount: '${page.totalCount}',
            limit: '${page.limit}',
            page: '${page.page}'
        });

        layui.use(['form', 'element'], function () {
            var element = layui.element;
            var form = layui.form;

            element.on('tab', function (data) {
                if (data.index == 0) {
                    window.location.href = "${ctx}/competition/result/personalRank.do?projectId=${project.id}";
                }
                else if (data.index == 1) {
                    window.location.href = "${ctx}/competition/result/groupRank.do?projectId=${project.id}";
                }
            });

            form.render('checkbox');
        });
    });
    txz.initHeader({
        nav: [{
            name: '我发布的项目',
            href: '${ctx}/competition/project/list.do'
        }, {
            name: '${project.title}',
            curr: true
        }, {
            name: '数据查看',
            curr: true
        }],
        btns: [{
            name: '返回',
            href: 'javascript:history.back();',
            icon: 'back'
        }]
    });

    function openDialog() {
        layer.open({
            type: 1,
            area: ['340px', '250px'],
            title: '成绩设置',
            content: $("#settingForm"),
            btn: ['确定', '取消'],
            success: function () {

            },
            end: function () {

            },
            yes: function () {
                //loading层
                var loadIndex = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                var _result = {};
                $(".schedule-item").each(function (index, ele) {
                    var id = $(ele).data("id");
                    var checked = $(ele).find("[type=checkbox]").prop("checked");
                    _result[id] = checked;
                });
                $.post("${ctx}/competition/schedule/updateOpenStatus.do", {
                    'projectId': '${project.id}',
                    'result': JSON.stringify(_result)
                }, function (ret) {
                    layer.close(loadIndex);
                    if (ret.success == true) {
                        util.layerMsgSuccess("成功", function () {
                            window.location.reload();
                        });
                    } else {
                        util.layerMsgError("失败")
                    }
                });
            }
        });
    }

    $(function () {
        var isRepeat = false;
        $.ajax({
            type: 'get',
            async: false, // 使用同步的方法
            data: {},
            dataType: 'json',
            success: function (res) {
                isRepeat = res.data.isExpire;
            },
            url: '${ctx}/system/member/expireCheck.do'
        });

        var importResultBtn = document.getElementById("importResultBtn");
        var upload_input = document.getElementById("upload_input");

        var resultSetBtn = document.getElementById("resultSetBtn");
        var exportExcelBtn = document.getElementById("exportExcelBtn");
        var downloadTemplateBtn = document.getElementById("downloadTemplateBtn");

        // 设置成绩
        resultSetBtn.addEventListener('click', function (e) {
            if (!isRepeat) {
                openDialog();
            } else {
                txz.openExpireDialog();
            }
            e.preventDefault();
        });

        // 导出Excel
        exportExcelBtn.addEventListener('click', function (e) {
            if (!isRepeat) {
                exportExcelData();
            } else {
                txz.openExpireDialog();
            }
            e.preventDefault();
        });

        // 下载模板
        downloadTemplateBtn.addEventListener('click', function (e) {
            if (!isRepeat) {
                window.location.href = '${ctx}/competition/result/createTemplate.do?type=1&projectId=${project.id}';
            } else {
                txz.openExpireDialog();
            }
            e.preventDefault();
        });

        // 导入成绩
        importResultBtn.addEventListener('click', function (e) {
            console.log('expireCheck');
            if (!isRepeat) {
                upload_input.click();
            } else {
                txz.openExpireDialog();
            }
            e.preventDefault();
        }, false);

        upload_input.addEventListener('change', function (e) {
            console.log(e.target.files[0].name);
            //loading层
            myLoadIndex = layer.msg('努力导入中,请耐心等待...', {
                icon: 16,
                shade: 0.1,
                time: 0
            });
            var formData = new FormData();
            formData.append("uploadFile", $("#upload_input")[0].files[0]);
            formData.append("projectId", '${project.id}');

            $.ajax({
                url: $("#userForm").attr('action'),
                type: 'post',
                data: formData,
                processData: false, // 告诉jQuery不要去处理发送的数据
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                beforeSend: function () {
                    console.log("正在进行，请稍候");
                },
                success: function (res) {
                    console.info('执行完了');
                    $("#userForm")[0].reset();
                },
                error: function (res) {
                    $("#userForm")[0].reset();
                    util.layerMsgError("上传异常：" + JSON.stringify(res));
                }
            });
            e.preventDefault();
        }, false);

        util.initWebSocket(function (event) {
            var jsonObj = JSON.parse(event.data);
            var totalNum = jsonObj.totalNum;
            var currentNum = jsonObj.currentNum;
            var successNum = jsonObj.successNum;
            var errorNum = jsonObj.errorNum;
            var resourceUrl = jsonObj.resourceUrl;
            var isComplete = jsonObj.isComplete;
            if (totalNum == currentNum && isComplete) {
                var message = "一共" + totalNum + "条数据；成功" + successNum + "条；错误" + errorNum + "条。";
                util.layerMsgSuccess(message, function () {
                    if (util.isValid(resourceUrl)) {
                        location.href = resourceUrl;
                        setTimeout(function () {
                            location.reload();
                        }, 500);
                    } else {
                        location.reload();
                    }
                })
            } else {
                var message = "一共有" + totalNum + "条数据，当前第" + currentNum + "条。";
                var length = $(".layui-layer-content.layui-layer-padding").length;
                if (length == 0) {
                    myLoadIndex = layer.msg('<i class="layui-layer-ico layui-layer-ico16"></i>' + message, {
                        icon: 16,
                        shade: 0.1,
                        time: 0
                    });
                } else {
                    $(".layui-layer-content.layui-layer-padding").html('<i class="layui-layer-ico layui-layer-ico16"></i>' + message);
                }
            }
        })
    });

    function exportExcelData() {
        layer.confirm('确认要导出Excel吗?', {
            icon: 3,
            title: '系统提示'
        }, function (index) {
            var url = "${ctx}/competition/result/exportAllMemberResult.do?projectId=${project.id}";
            //loading层
            var loadIndex = layer.load(1, {
                shade: [0.1, '#fff'] //0.1透明度的白色背景
            });
            $.post(url, $("#myForm").serialize(), function (res) {
                top.layer.close(loadIndex);
                if (res.success) {
                    window.location.href = res.data;
                } else {
                    util.layerMsgError(res.description)
                }
            });
            top.layer.close(index);
        });
    }
</script>
</body>
</html>